package gu.sql2java.excel.aspect.spring;

import static com.google.common.base.Preconditions.checkState;
import static net.gdface.web.DefaultResponseFactory.loadResponseFactory;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

import net.gdface.web.Response;

public class ResponseParser implements ReturnValueParser {
	
	@Override
	public Class<?> getReturnType(){
		return Response.class;
	}
	@Override
	public ReturnInfo parse(ReturnInfo input) throws Exception{
		Response value = (Response)input.returnValue;
		/** 方法返回类型为 Response 是不应该返回 null*/
    	checkState(null != input.returnValue,"%s return type is Response,must not be null",input.invokeMethod.getName());
    	Object returnValue = value.getResult();
    	Object target = value.delegate();
    	checkState(null != target,"Response.delegate() must not return null");
    	Method invokeMethod = target.getClass().getMethod(input.invokeMethod.getName(), input.invokeMethod.getParameterTypes());
    	Type returnType = invokeMethod.getGenericReturnType();
    	return new ReturnInfo(returnValue,invokeMethod,returnType);
	}
	@Override
	public Object onGetParameter(Object returnValue,Object parameterValue){
		Response response;
		if(returnValue instanceof Response){
			response = (Response)returnValue;
		}else{
			response = loadResponseFactory().createResponse();
		}
		response.setResult(parameterValue);
		return response;
	}
	@Override
	public void onError(Object returnValue,Exception e) throws Exception{
		((Response)returnValue).onError(e);
	}
	@Override
	public boolean isSuccess(Object returnValue){
		return (returnValue instanceof Response)&& ((Response)returnValue).isSuccess();
	}
}
